package com.ays.mesbackbone.common.distributed.id;

/**
 * <p>Title： SnowflakeWorker </p>
 * <p>Description：Snowflake Id Worker </p>
 *
 * @author sujunxuan
 * @version V1.0
 * @date 2019/7/13 16:54
 */
public class SnowflakeWorker {

    /**
     * 起始的时间戳
     */
    private static final long START_STAMP = 1596444488000L;

    /**
     * 每一部分占用的位数
     */
    private static final long SEQUENCE_BIT = 12;
    private static final long MACHINE_BIT = 8;
    private static final long DATACENTER_BIT = 2;
    /**
     * 每一部分的最大值
     */
    public static final long MAX_MACHINE_NUM = ~(-1L << MACHINE_BIT);
    public static final long MAX_DATACENTER_NUM = ~(-1L << DATACENTER_BIT);
    private static final long MAX_SEQUENCE = ~(-1L << SEQUENCE_BIT);

    /**
     * 每一部分向左的位移
     */
    private static final long MACHINE_LEFT = SEQUENCE_BIT;
    private static final long DATACENTER_LEFT = SEQUENCE_BIT + MACHINE_BIT;
    private static final long TIMESTAMP_LEFT = DATACENTER_LEFT + DATACENTER_BIT;

    private final long datacenterId;
    private final long machineId;
    private long sequence = 0L;
    private long lastStamp = -1L;
    private byte sequenceOffset;

    public SnowflakeWorker(long datacenterId, long machineId) {
        if (datacenterId > MAX_DATACENTER_NUM || datacenterId < 0) {
            throw new IllegalArgumentException("datacenterId can't be greater than MAX_DATACENTER_NUM or less than 0");
        }
        if (machineId > MAX_MACHINE_NUM || machineId < 0) {
            throw new IllegalArgumentException("machineId can't be greater than MAX_MACHINE_NUM or less than 0");
        }
        this.datacenterId = datacenterId;
        this.machineId = machineId;
    }

    /**
     * 产生下一个ID
     *
     * @return id
     */
    public synchronized long nextId() {
        long currStamp = getNewStamp();
        if (currStamp < lastStamp) {
            throw new IllegalArgumentException("Clock moved backwards.  Refusing to generate id");
        }

        if (currStamp == lastStamp) {
            //相同毫秒内，序列号自增
            sequence = (sequence + 1) & MAX_SEQUENCE;
            //同一毫秒的序列数已经达到最大
            if (sequence == 0L) {
                currStamp = getNextMill();
            }
        } else {
            // 时间戳改变，毫秒内序列重置
            vibrateSequenceOffset();
            sequence = sequenceOffset;
        }

        lastStamp = currStamp;

        return (currStamp - START_STAMP) << TIMESTAMP_LEFT
                | datacenterId << DATACENTER_LEFT
                | machineId << MACHINE_LEFT
                | sequence;
    }

    private long getNextMill() {
        long mill = getNewStamp();
        while (mill <= lastStamp) {
            mill = getNewStamp();
        }
        return mill;
    }

    private long getNewStamp() {
        return System.currentTimeMillis();
    }

    private void vibrateSequenceOffset() {
        // 总是返回 0 或者 1
        sequenceOffset = (byte) (~sequenceOffset & 1);
    }
}
